package com.study.spring.netty.time_client;

import cn.hutool.core.thread.NamedThreadFactory;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Random;

/**
 * @author zhang
 * @version 1.0
 * @date 2019/5/7 0007
 * @since jdk1.8
 */
public class TimeClient {

    public static void main(String[] args) throws InterruptedException {

        final Channel[] channel = new Channel[1];

        String host = "127.0.0.1";
        int port = 8080;
        EventLoopGroup workGroup = new NioEventLoopGroup(5, new NamedThreadFactory("helloJ", false));
        try {

            Bootstrap b = new Bootstrap();
            b.group(workGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.option(ChannelOption.TCP_NODELAY, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new TimeClientDecode(), new TimeClientHandler()).addFirst(new TimeClientEncode());
                }
            });

            ChannelFuture f = b.connect(host, port).sync();
            channel[0] = f.channel();

//                for (int i = 0; i < 5000000; i++) {
//                    String msg = "what is the time?";
////                ByteBuf byteBuf = Unpooled.buffer();
////                byteBuf.writeBytes(msg.getBytes(StandardCharsets.UTF_8));
//                    channel[0].writeAndFlush(msg);
//                }
//                System.out.println("客户端发送完毕！");
//                channel[0].closeFuture( ).sync( );
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        String msg = "what is the time %d ?";
        for (int i = 0; i < 5; i++) {
            channel[0].writeAndFlush(new Request(String.format(msg, i * new Random().nextLong())));
        }

        Thread.sleep(10000);
        System.out.println("休眠完成!");
        System.out.println(channel[0].isOpen());
        channel[0].writeAndFlush(new Request("hello"));


        Thread.sleep(21000);
        System.out.println("客户端发送完毕！");

        System.out.println(channel[0].isOpen());
        channel[0].close();
        workGroup.shutdownGracefully();
    }
}
